package com.cuit.freshmanMS.util;

import com.cuit.freshmanMS.util.result.CommonResult;
import com.cuit.freshmanMS.util.result.ResultCode;
import com.cuit.freshmanMS.util.result.ResultUtil;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class FileUtils {

    /**
     * 处理文件下载
     * @param response
     * @param fileName
     * @return
     */
    public static CommonResult<Boolean> downloadFile(HttpServletResponse response, String fileName){

        if (StringUtils.isEmpty(fileName)) {
            return ResultUtil.fail(ResultCode.PARAM_IS_BLANK);
        }

        //设置文件路径
        File file = new File("src/main/resources/templates/" + fileName);

        response.setHeader("content-type", "application/octet-stream");
        // 设置强制下载不打开
        response.setContentType("application/force-download");
        // 设置文件名
        response.setCharacterEncoding("UTF-8");
        try {
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("application/x-msdownload");

        byte[] buffer = new byte[1024];
        InputStream fis = null;
        BufferedInputStream bis = null;

        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        file.delete();
        return ResultUtil.success();
    }
}
